import { Button, message, Modal, Input } from 'antd';
import React, { useState, useRef, useEffect, useContext } from 'react';
import ProTable from '@ant-design/pro-table';
import AddForm from './components/AddForm';
import {
  getMaintenanceList,
  addMaintenanceList,
  updateMaintenanceList,
  deleteMaintenanceList,
} from './service';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { UserContext } from '@/layouts/UserProvider';

const TableList = () => {
  const [updateModalVisible, handleDetailModalVisible] = useState(false);
  const [group, setGroup] = useState('');
  const [type, setType] = useState('1');
  const actionRef = useRef();
  const userCtx = useContext(UserContext);
  const permits = userCtx.userPermits;
  const [activekey, setActiveKey] = useState('1');
  const userInfo = userCtx.userInfo;
  console.log('userCtx.userPermits=======', permits);
  //添加
  const handleAdd = async (type, fields) => {
    const hide = message.loading('正在添加');
    try {
      await addMaintenanceList({
        type: parseInt(type),
        card_id: fields.card_id,
        operator: fields.operator,
        phone: fields.phone,
        group: fields.group,
        content: fields.content,
      }).then((data) => {
        hide();
        if (data.code == '200') {
          message.success('添加成功');
          if (actionRef.current) {
            actionRef.current.reload();
          }
          handleDetailModalVisible(false);
        } else {
          message.error(data.msg);
        }
      });
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
    }
  };
  //更新
  const handleUpdate = async (fields) => {
    const hide = message.loading('正在修改');
    try {
      const res = await updateMaintenanceList({
        id: fields.id,
        card_id: fields.card_id,
        operator: fields.operator,
        phone: fields.phone,
        group: fields.group,
        content: fields.content,
      });
      hide();
      if (res.code == '200') {
        message.success('修改成功');
        if (actionRef.current) {
          actionRef.current.reload();
        }
        handleDetailModalVisible(false);
      } else {
        message.error('修改失败请重试！');
      }
    } catch (error) {
      hide();
      message.error('修改失败请重试！');
    }
  };
  useEffect(() => {}, []);
  //删除
  const handleDel = (record) => {
    Modal.confirm({
      icon: <ExclamationCircleOutlined />,
      content: '是否要删除？',
      okText: '确认',

      cancelText: '取消',
      onOk: () => {
        deleteMaintenanceList({ id: record.id }).then((data) => {
          //重新加载
          if (actionRef.current) {
            actionRef.current.reload();
          }
        });
      },
    });
  };
  const renderBadge = (count, active = false) => {
    return (
      <text
        style={{
          marginTop: -2,
          marginLeft: 4,
          color: active ? '#1890FF' : '#999',
          backgroundColor: active ? '#E6F7FF' : '#eee',
        }}
      />
    );
  };
  const columns = [
    {
      title: '日期',
      dataIndex: 'date',
      search: false,
      with: '200',
    },
    {
      title: '负责人员',
      search: false,
      dataIndex: 'operator',
      ellipsis: {
        showTitle: false,
      },
    },
    {
      title: '联系方式',
      search: false,
      dataIndex: 'phone',
      renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
        if (status === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            // value 和 onchange 会通过 form 自动注入。
            <Input
              // 自定义配置
              placeholder="请输入"
              maxLength={11}
            />
          );
        }
        return defaultRender(_);
      },
    },
    {
      title: '车牌号',
      search: false,
      dataIndex: 'card_id',
      ellipsis: {
        showTitle: false,
      },
    },
    {
      title: '部门',
      search: false,
      dataIndex: 'group',
    },
    {
      title: '维修内容',
      search: false,
      dataIndex: 'content',
      ellipsis: {
        showTitle: false,
      },
    },
    {
      title: '操作',
      search: false,
      dataIndex: 'delete',
      render: (_, record) => {
        let res = [];
        if (['1', '4'].includes(String(userInfo?.type))) {
          if (permits.includes('updateMaintenance')) {
            res.push(
              <Button
                size="small"
                key="edit"
                style={{ marginRight: 15 }}
                onClick={() => {
                  handleDetailModalVisible(record);
                  setGroup(1);
                }}
              >
                修改
              </Button>,
            );
          }
          if (permits.includes('deleteMaintenance')) {
            res.push(
              <Button
                size="small"
                key="delect"
                onClick={() => {
                  handleDel(record);
                  setGroup(2);
                }}
              >
                删除
              </Button>,
            );
          }
        }
        return res;
      },
    },
  ];
  return (
    <>
      <ProTable
        actionRef={actionRef}
        rowKey="key"
        search={false}
        columns={columns}
        request={async (params, sorter, filter) => {
          try {
            // params.current;
            params.is_total = true;
            params.limit = params.pageSize;
            params.offset = (params.current - 1) * params.pageSize;
            params.is_total = true;
            params.type = parseInt(type);
            let res = await getMaintenanceList({ ...params, sorter, filter });
            if (res.data == null && res.total != 0) {
              params.current = params.current - 1;
              params.offset = (params.current - 1) * params.pageSize;
              res = await getMaintenanceList({ ...params, sorter, filter });
            }
            return {
              data: JSON.stringify(res.data) !== '{}' ? res.data : [],
              success: true,
              total: res.total || 0,
            };
          } catch (error) {
            return { data: [], success: false, total: 0 };
          }
        }}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: activekey,
            items: [
              {
                key: '1',
                label: <span>维修{renderBadge(99, activekey === '1')}</span>,
              },
              {
                key: '2',
                label: <span>保养</span>,
              },
              {
                key: '3',
                label: <span>调试{renderBadge(30, activekey === '3')}</span>,
              },
              {
                key: '4',
                label: <span>改装{renderBadge(30, activekey === '4')}</span>,
              },
              {
                key: '5',
                label: <span>软件升级{renderBadge(30, activekey === '5')}</span>,
              },
            ],
            onChange: (key) => {
              setActiveKey(key);
              setType(key);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            },
          },
          actions: [
            ['1', '4'].includes(String(userInfo?.type)) && permits.includes('addMaintenance') && (
              <Button
                key="primary"
                type="primary"
                onClick={() => {
                  handleDetailModalVisible(true);
                  setGroup(0);
                }}
              >
                新增
              </Button>
            ),
          ],
        }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          hideOnSinglePage: false,
          showTotal: (total) => `共有 ${total} 条记录`,
          pageSize: 10,
        }}
      />
      <AddForm
        onSubmit={async (value) => {
          console.log('type', type);
          //添加
          if (group == 0) {
            await handleAdd(type, value);
          }
          //更新
          if (group == 1) {
            await handleUpdate(value);
          }
        }}
        onCancel={() => {
          handleDetailModalVisible(false);
        }}
        group={group}
        updateModalVisible={updateModalVisible}
        type={type}
      />
    </>
  );
};

export default TableList;
